from django.shortcuts import render
from django.views import View
import logging
from .registerforms import RegisterForm,LoginForm
from .models import User
from virefy.json_res import json_response
from virefy.json_res import Code
# Create your views here.
class LoginView(View):
    def get(self,request):
        return render(request,"user/login.html")
    def post(self,request):
        form=LoginForm(request.POST,request=request)
        if form.is_valid():
            print(json_response(errmsg="恭喜你登录成功"))
            return json_response(errmsg="恭喜你登录成功")
        else:
            error_list=[]
            for item in form.errors.get_json_data().values():
                error_list.append(item[0].get("message"))
            error_msg='/'.join(error_list)
            return json_response(errno=Code.LOGINERR,errmsg=error_msg)
# def  register(request):
#     return render(request,"user/register.html")
# logger=logging.getLogger("django")
# logger.setLevel(logging.DEBUG)
# st=logging.StreamHandler()
# st.setLevel(logging.INFO)
# formart=logging.Formatter(
#     '时间:%(asctime)s'
#     '等级:%(levelname)s'
#     '错误信息:%(message)s'
# )
# st.setFormatter(formart)
# logger.addHandler(st)

class RegisterView(View):
    def get(self,request):
        return render(request,"user/register.html")
    def post(self,request):
        # logger.info("提交数据")
        form=RegisterForm(request.POST)
        # logger.info(self.request.POST,'接收数据OK')
        if form.is_valid():
            username=form.cleaned_data.get('username')
            password=form.cleaned_data.get('password')
            mobile=form.cleaned_data.get('telephone')
            User.objects.create_user(username=username,password=password,mobile=mobile)
            return json_response(errmsg="恭喜你，注册成功")
        else:
            error_msg_list=[]
            for item in form.errors.get_json_data().values():
                error_msg_list.append(item[0].get('message'))
            error_msg_str='/'.join(error_msg_list)
            return json_response(errno=Code.UNKOWNERR,errmsg=error_msg_str)


